// Express web framework for web develop
// cnpm install express --save
// median component for parse json text url raw
// cnpm install body-parser --save
// cookie tool
// cnpm install cookie-parser --save
// form data tool
// cnpm install multer --save
// query installed lib
// cnpm list express
var express = require('express');
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
var util = require('util');
var cookieParser = require('cookie-parser');

var app = express();

// static file : css / js / image
app.use('/static', express.static('static'));

app.use(cookieParser());
// for url encode
app.use(bodyParser.urlencoded({extended: false}));
// upload file
app.use(multer({dest: '/tmp/'}).array('image'));

// all path uri must be start with /
app.get('/', (req, resp) => {
	console.log('query parameter => ', req.query.name);
	resp.send('hello world');
});

app.post('/', (req, resp) => {
	console.log('post parameter => ', req.query.name);
	resp.send('hello world =>' + req.query.name);
});

app.get('/abc*', (req, resp) => {
	console.log('request =>', JSON.stringify(req));
	resp.send('regexp path');
});

// static file : css / js / image
// app.use('/static', express.static('static'));

// app.use(cookieParser());
// for url encode
// app.use(bodyParser.urlencoded({extended: false}));
// upload file
// app.use(multer({dest: '/tmp/'}).array('image'));
app.post('/upload', (req, resp) => {
	console.log(req);
	console.log('cookie =>', util.inspect(req.cookies));
	var des_file = __dirname + '/temp/' + req.files[0].originalname;
	fs.readFile(req.files[0].path, (err, data) => {
		fs.writeFile(des_file, data, err => {
			if (err) {
				console.log(err);
			} else {
				respData = {
					message: 'File upload successfully',
					filename: req.files[0].originalname
				};
			}
			console.log(respData);
			resp.end(JSON.stringify(respData));
		});
	});
});


var server = app.listen(8080, () => {
	var host = server.address().address;
	var port = server.address().port;
	console.log('access url => ', host, port);
});


